package com.kevin.Code.Tree;

/**
 * @author Vinlee Xiao
 * @Classname ImplementTriePrefixTree
 * @Description Leetcode 208. 实现 Trie (前缀树) 中等难度 经典题目 参考官方题解
 * @Date 2021/11/19 10:41
 * @Version 1.0
 */
public class Trie {
    private Trie[] children;
    //判断当前结点是结尾结点
    private boolean isEnd;

    //初始化
    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }

    /**
     * @param word
     */
    public void insert(String word) {

        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            //当前结点的孩子结点的索引字符为空
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        //标志当前结点为最后一个字符结点
        node.isEnd = true;
    }

    /**
     * @param word
     * @return
     */
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }

    /**
     * @param prefix
     * @return
     */
    public boolean startsWith(String prefix) {
        Trie node = searchPrefix(prefix);
        return node != null;
    }

    /**
     * @param word
     * @return
     */
    private Trie searchPrefix(String word) {
        Trie node = this;

        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';

            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
        }

        return node;
    }
}
